package cn.zjj.user.util;

import cn.zjj.basic.jwt.JwtUtils;
import cn.zjj.basic.jwt.Payload;
import cn.zjj.basic.jwt.RsaUtils;
import cn.zjj.basic.util.LoginData;
import cn.zjj.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

public class LoginContext {

    public static Logininfo getLogininfo(HttpServletRequest request){
        try {
            String jwtToken = request.getHeader("token");
            if(jwtToken!=null) {//请求头中有token
            /*//根据token进redis中查对应的value,
            Object logininfo = redisTemplate.opsForValue().get(jwtToken);*/
                //弃用redis,改用jwt
                //获取公钥,用已解密
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //因为jwt过期就会报错所以try
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
                //如果还存在,即还没过期
                if (payload != null) {
                    Logininfo logininfo = payload.getLoginData().getLogininfo(); //获取登录信息
                    return logininfo;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
